<template>
  <div class="bgc-default pad-20">

    <!-- 平台类型 -->
    <third-platform-head @platformTypeChange="platformTypeChange"></third-platform-head>

    <div class="bg-color-white pad-l-20 pad-r-20 mar-t-15 pad-t-20">
      <!--顶部搜索 -->
      <div class="top-operate-default pad-t-15">
        <div class="search-item">
          <label>搜索商品：</label>
          <el-input style="width: 200px" v-model="searchListQuery.title" placeholder="请输入商品名称"></el-input>
          <label class="mar-l-20">更新结果：</label>
          <el-select v-model="searchListQuery.updateStatus" placeholder="更新结果" @change="updateStatusChange">
            <el-option label="全部" value=""></el-option>
            <el-option label="未同步" value="0"></el-option>
            <el-option label="成功" value="1"></el-option>
            <el-option label="失败" value="2"></el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button plain @click="resetSearch">重置</el-button>
          </el-button-group>
          <label class="mar-l-20">店铺：</label>
          <el-select v-model="shopId" placeholder="下载商品所属店铺" class="expend">
            <el-option v-for="item in shopList" :key="item.shopId" :label="item.shopName" :value="item.shopId">
            </el-option>
          </el-select>
          <el-button class="mar-l-20" @click="downloadGoods">下载整店商品</el-button>
          <el-button style="margin-left: 50px" @click="updateBatchStock(0)">更新所选商品库存</el-button>
          <el-button @click="updateBatchStock(1)">更新全部商品库存</el-button>
        </div>
      </div>
      <div class="pad-t-15 pad-b-15 font-14 v-align-c">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="dataList" v-loading="listLoading" @selection-change="handleSelectionChange" element-loading-text="加载中">
          <el-table-column width="55px" type="selection"></el-table-column>
          <el-table-column width="280px" label="商品名称" fixed="left">
            <template slot-scope="scope">
              <span>{{ scope.row.title }}</span><br/>
              <span style="color: #2d8cf0">[平台编码：{{ scope.row.externalCode }}]</span>
            </template>
          </el-table-column>
          <el-table-column label="店铺商品SKU ID" prop="externalSkuId"></el-table-column>
          <el-table-column label="规格" prop="skuDetail"></el-table-column>
          <el-table-column label="下载时间" prop="createTime"></el-table-column>
          <el-table-column label="更新库存时间" prop="stockUpdateTime"></el-table-column>
          <el-table-column label="更新结果" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.updateStatus === 0">待更新</span>
              <span v-if="scope.row.updateStatus === 1">成功</span>
              <template v-if="scope.row.updateStatus === 2">
                <span>失败</span><br/>
                <el-tooltip class="item" effect="dark" :content="scope.row.errorRemark" placement="top-start">
                  <span style="color: #2d8cf0">失败原因</span>
                </el-tooltip>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import thirdAuth from '../components/third-auth'
  import thirdPlatformHead from '../components/third-platform-head'
  import { listThirdShop } from '@/api/user/third-shop'
  import { pageThirdGoodsSku, updateBatchStock, downloadGoodsSku } from '@/api/third/thirdGoodsSku'
  export default {
    components: { thirdPlatformHead },
    mixins: [thirdAuth],
    data() {
      return {
        // 查询条件
        searchListQuery: {
          currentPage: 1,
          size: 10,
          title: '',
          updateStatus: ''
        },
        // 平台类型
        platformType: 1,
        // 店铺id
        shopId: '',
        listLoading: false,
        total: 0,
        // 店铺集合
        shopList: [],
        // 商品集合
        dataList: [],
        multipleSelection: [],
        allChecked: false
      }
    },
    // 初始化页面
    created() {
      this.initListThirdShop()
    },
    mounted() {
    },
    methods: {
      // 平台类型切换事件
      platformTypeChange(platformType) {
        this.platformType = platformType
        this.initListThirdShop()
      },
      // 获取第三方店铺列表
      initListThirdShop() {
        const params = {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getMemberId(),
          platformType: this.platformType
        }
        listThirdShop(params).then(response => {
          if (response.isError) return
          if (response.data) {
            this.shopId = response.data[0] && response.data[0].shopId
            this.shopList = response.data
          }
          this.init()
        })
      },
      // 获取商品列表
      init() {
        this.searchListQuery.shopId = this.shopId
        this.searchListQuery.platformType = this.platformType
        pageThirdGoodsSku(this.searchListQuery).then(response => {
          if (response.isError) return
          this.listLoading = false
          this.total = response.data.total
          this.dataList = response.data.records
        })
      },
      // 结果状态切换事件
      updateStatusChange() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      // 查询事件
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      // 重置事件
      resetSearch() {
        this.searchListQuery = {
          currentPage: 1,
          size: 10,
          title: '',
          updateStatus: ''
        }
        this.init()
      },
      // 下载商品事件
      downloadGoods() {
        const redirectUrl = '/#/' + (this.getMemberId() ? 'shop' : 'channel') + '/update-stock/index?platformType=' + this.platformType
        // 校验access_token是否存在
        this.checkAccessToken(this.platformType, this.shopId, redirectUrl, true).then(response => {
          if (response) {
            this.$confirm('下载数据量可能会比较大，需要耐心等候处理，确定下载？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              const data = {
                shopId: this.shopId,
                memberId: this.getMemberId(),
                enterpriseId: this.getEnterpriseId(),
                platformType: this.platformType
              }
              downloadGoodsSku(data).then(response => {
                if (response.isError) return
                this.$message({ type: 'success', message: '成功!' })
                this.init()
              })
            }).catch(() => {
              this.$message({ type: 'info', message: '已取消' })
            })
          }
        })
      },
      // 更新商品库存
      updateBatchStock(status) {
        if (!this.shopId) {
          this.$message({ type: 'error', message: '请先选择店铺' })
          return
        }
        const thirdGoodsSkuIds = []
        if (status === 0) {
          if (this.multipleSelection.length > 0) {
            this.multipleSelection.forEach((item) => {
              thirdGoodsSkuIds.push(item.thirdGoodsSkuId)
            })
          } else {
            this.$message.error('请选择要操作数据')
            return
          }
        }
        const data = {
          thirdGoodsSkuIds: thirdGoodsSkuIds,
          memberId: this.getMemberId(),
          enterpriseId: this.getEnterpriseId(),
          platformType: this.platformType,
          shopId: this.shopId
        }
        this.$confirm('确定要更新所选平台上店铺中商品的库存？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const redirectUrl = '/#/' + (this.getMemberId() ? 'shop' : 'channel') + '/update-stock/index?platformType=' + this.platformType
          this.checkAccessToken(this.platformType, this.shopId, redirectUrl, true).then(response => {
            updateBatchStock(data).then(response => {
              if (response.isError) return
              if (response.data > 0) {
                this.$message.error('更新库存发生错误，具体原因请查看更新结果')
              } else {
                this.$message({ type: 'success', message: '成功!' })
              }
              this.init()
            })
          })
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消' })
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.init()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.init()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.dataList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.dataList.length) {
          this.dataList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 90px;
    height: 90px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
  .expend{
    /deep/.el-input{
      width: 180px;
    }
  }
  .table-container{
    /deep/.el-table th > .cell{
      padding-left: 14px;
    }
  }
</style>
